package com.lexue.articlesync.controller;

import com.lexue.articlesync.util.DatabaseExporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 数据库导出控制器
 */
@RestController
@RequestMapping("/api/database")
public class DatabaseExportController {

    @Autowired
    private DatabaseExporter databaseExporter;

    /**
     * 导出数据库备份文件
     */
    @GetMapping("/export")
    public ResponseEntity<?> exportDatabase() {
        try {
            // 生成备份文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileName = "articlesync_backup_" + timestamp + ".sql";
            String filePath = "./backup/" + fileName;
            
            // 确保备份目录存在
            File backupDir = new File("./backup");
            if (!backupDir.exists()) {
                backupDir.mkdirs();
            }
            
            // 执行导出
            databaseExporter.exportDatabase(filePath);
            
            // 返回下载链接
            return ResponseEntity.ok()
                    .body("数据库导出成功！文件路径: " + filePath + 
                          "\n下载链接: /api/database/download/" + fileName);
            
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body("数据库导出失败: " + e.getMessage());
        }
    }

    /**
     * 下载备份文件
     */
    @GetMapping("/download/{fileName}")
    public ResponseEntity<Resource> downloadBackup(String fileName) {
        try {
            File file = new File("./backup/" + fileName);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            
            Resource resource = new FileSystemResource(file);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
            
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 列出所有备份文件
     */
    @GetMapping("/backups")
    public ResponseEntity<?> listBackups() {
        try {
            File backupDir = new File("./backup");
            if (!backupDir.exists()) {
                return ResponseEntity.ok("备份目录不存在，尚无备份文件");
            }
            
            File[] files = backupDir.listFiles((dir, name) -> name.endsWith(".sql"));
            if (files == null || files.length == 0) {
                return ResponseEntity.ok("暂无备份文件");
            }
            
            StringBuilder result = new StringBuilder("备份文件列表:\n");
            for (File file : files) {
                result.append("- ").append(file.getName())
                      .append(" (").append(file.length()).append(" bytes)")
                      .append(" - 创建时间: ").append(new java.util.Date(file.lastModified()))
                      .append("\n");
            }
            
            return ResponseEntity.ok(result.toString());
            
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body("获取备份文件列表失败: " + e.getMessage());
        }
    }
}